<template>
  <n-grid x-gap="10" y-gap="10" :col="24">
    <n-gi span="6" v-if="props.showAdd">
      <div class="custom-choose-item" @click.stop="handleClickAdd">
        <n-icon size="20">
          <AddOutline />
        </n-icon>
      </div>
    </n-gi>
    <n-gi span="6" v-for="category in categories" :key="category.id">
      <div
        class="custom-choose-item flex items-center justify-center"
        @click.stop="handleSelectCategory(category)"
      >
        <div class="image">
          <n-image
            preview-disabled
            width="56"
            height="56"
            :src="category.icon"
            fallback-src="https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg"
          />
        </div>
        <div class="title">
          <span> {{ category.name }} </span>
        </div>
      </div>
    </n-gi>
  </n-grid>
  <category-modal
    v-model:show="showModalResult.show"
    :action-type="showModalResult.actionType"
    :form-data="showModalResult.categoryDetail"
    title="新增产品类别"
    @create-success="handleCreateSuccess"
    @close="showModalResult.show = false"
    @cancel="showModalResult.show = false"
  />
</template>
<script setup lang="ts" name="ChooseCategory">
import { ref, onMounted, reactive } from "vue";
import { debounce, get } from "lodash-es";
import { AddOutline } from "@vicons/ionicons5";
import { getCategories } from "@/api/product/category.api";
import { Category } from "@/types/model/product/vos/category.vo";
import CategoryModal from "@/components/biz/categoryModal/index.vue";
import type { IChooseCategoryProps } from "./props";
import { ActionTypeEnum } from "@/enums/actionTypeEnum";

const emits = defineEmits(["selected"]);

const props = withDefaults(defineProps<IChooseCategoryProps>(), {
  showAdd: true,
  selectedCategoryId: "",
});

const initLoading = ref<boolean>(true);
const categories = ref<Category[]>([]);

const showModalResult = reactive({
  show: false,
  categoryDetail: {} as Category,
  actionType: ActionTypeEnum.ADD,
});
const handleGetAllCategories = async () => {
  initLoading.value = true;
  try {
    const res = await getCategories({ page: 1, pageSize: 1000, status: "1" });
    categories.value = get(res, "result.records") || [];
  } finally {
    initLoading.value = false;
  }
};

const handleClickAdd = () => {
  showModalResult.actionType = ActionTypeEnum.ADD;
  showModalResult.categoryDetail = {} as Category;
  showModalResult.show = true;
};

const handleSelectCategory = debounce(function (payload: Category) {
  console.log(payload);
  emits("selected", payload);
}, 200);

const handleCreateSuccess = () => {
  handleGetAllCategories();
  showModalResult.show = false;
};

onMounted(() => {
  handleGetAllCategories();
});
</script>
